package me.sdevil507.org.repository;

import me.sdevil507.org.po.OrgResourcePo;
import me.sdevil507.platform.po.PlatResourcePo;
import me.sdevil507.supports.jpa.BaseJpaDslRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * 机构资源表[OrgResourceRepository]
 *
 * @author sdevil507
 * created on 2020-06-23 18:43:30
 */
public interface OrgResourceRepository extends BaseJpaDslRepository<OrgResourcePo, Long> {

    /**
     * 根据资源id列表查询出资源列表
     *
     * @param resourceIds 资源id列表
     * @return 资源列表
     */
    Set<OrgResourcePo> findAllByIdIn(List<Long> resourceIds);

    /**
     * 根据资源code列表查询出资源列表
     *
     * @param resourceCodes 资源code列表
     * @return 资源列表
     */
    Set<OrgResourcePo> findAllByCodeIn(List<String> resourceCodes);

    /**
     * 根据parentId获取同级资源
     *
     * @param parentId 父模块id
     * @return 同级资源列表
     */
    List<OrgResourcePo> findAllByParentIdOrderByCodeDesc(Long parentId);


    @Transactional(rollbackFor = Exception.class)
    @Modifying(clearAutomatically = true)
    @Query(nativeQuery = true, value = "delete from biz_org_role_res_rel a where a.role_id=:roleId and a.res_id =:resourceId")
    void deleteOrgResourceRel(@Param("roleId") Long roleId, @Param("resourceId") Long resourceId);

    @Modifying(clearAutomatically = true)
    @Query(nativeQuery = true, value = "SELECT\n" +
            "\tbor.* \n" +
            "FROM\n" +
            "\tplat_resource bor\n" +
            "\tLEFT JOIN biz_org_role_res_rel bo ON bo.res_id = bor.id \n" +
            "WHERE\n" +
            "\tbo.role_id =:roleId \n" +
            "\tAND bor.classify =:classify")
    Set<PlatResourcePo> getOrgValueResourceRel(@Param("roleId") Long roleId, @Param("classify") Integer classify);
}